package edu.suda.basic.sigar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.thoughtworks.xstream.XStream;

public class NIC
{

	private NetInterfaceConfig	config;
	private NetInterfaceStat	stat;
	private long				rxbps;
	private long				txbps;

	public NIC()
	{
	}

	public void populate(Sigar sigar, String name) throws SigarException
	{

		config = sigar.getNetInterfaceConfig(name);

		try
		{

			long start = System.currentTimeMillis();
			NetInterfaceStat statStart = sigar.getNetInterfaceStat(name);
			long rxBytesStart = statStart.getRxBytes();
			long txBytesStart = statStart.getTxBytes();
			Thread.sleep(1000);
			long end = System.currentTimeMillis();
			NetInterfaceStat statEnd = sigar.getNetInterfaceStat(name);
			long rxBytesEnd = statEnd.getRxBytes();
			long txBytesEnd = statEnd.getTxBytes();

			rxbps = (rxBytesEnd - rxBytesStart) * 8 / (end - start) * 1000;
			txbps = (txBytesEnd - txBytesStart) * 8 / (end - start) * 1000;
			stat = sigar.getNetInterfaceStat(name);
		}
		catch (SigarException e)
		{

		}
		catch (Exception e)
		{

		}
	}

	public static NIC gather(Sigar sigar, String name) throws SigarException
	{

		NIC data = new NIC();
		data.populate(sigar, name);
		return data;
	}

	public NetInterfaceConfig getConfig()
	{
		return config;
	}

	public NetInterfaceStat getStat()
	{
		return stat;
	}

	public long getRxbps()
	{
		return rxbps;
	}

	public long getTxbps()
	{
		return txbps;
	}

	public static void main(String[] args) throws Exception
	{
		Sigar sigar = new Sigar();
		String[] netIfs = sigar.getNetInterfaceList();
		List netIfList = new ArrayList();
		for (String name : netIfs)
		{
			NIC netIfData1 = NIC.gather(sigar, name);
			netIfList.add(netIfData1);
		}
		XStream xstream = new XStream();
		xstream.alias("NetInterfaceDatas", List.class);
		xstream.alias("NetInterfaceData", NIC.class);
		System.out.println(xstream.toXML(netIfList));
	}
}
